#!/usr/bin/env bash

cd $(dirname $0)/..
app_root=$(pwd)
sidekiq_workers=${SIDEKIQ_WORKERS:-1}
sidekiq_queues=${SIDEKIQ_QUEUES:-*} # Queues to listen to; default to `*` (all)
sidekiq_pidfile="$app_root/tmp/pids/sidekiq-cluster.pid"
sidekiq_logfile="$app_root/log/sidekiq.log"
gitlab_user=$(ls -l config.ru | awk '{print $3}')

trap cleanup EXIT

warn()
{
  echo "$@" 1>&2
}

get_sidekiq_pid()
{
  if [ ! -f $sidekiq_pidfile ]; then
    warn "No pidfile found at $sidekiq_pidfile; is Sidekiq running?"
    return
  fi

  cat $sidekiq_pidfile
}

stop()
{
  sidekiq_pid=$(get_sidekiq_pid)

  if [ $sidekiq_pid ]; then
    kill -TERM $sidekiq_pid
  fi
}

restart()
{
  if [ -f $sidekiq_pidfile ]; then
    stop
  fi

  start_sidekiq "$@"
}

start_sidekiq()
{
  cmd="exec"
  chpst=$(command -v chpst)

  if [ -n "$chpst" ]; then
    cmd="${cmd} ${chpst} -P"
  fi

  # sidekiq-cluster expects an argument per process.
  for (( i=1; i<=$sidekiq_workers; i++ ))
  do
    processes_args+=("${sidekiq_queues}")
  done

  ${cmd} bin/sidekiq-cluster "${processes_args[@]}" -P $sidekiq_pidfile -e $RAILS_ENV "$@" 2>&1 | tee -a $sidekiq_logfile
}

cleanup()
{
  stop
}

action="$1"
shift

case "$action" in
  stop)
    stop
    ;;
  start)
    restart "$@" &
    ;;
  start_foreground)
    start_sidekiq "$@"
    ;;
  restart)
    restart "$@" &
    ;;
  *)
    echo "Usage: RAILS_ENV=<env> SIDEKIQ_WORKERS=<n> $0 {stop|start|start_foreground|restart}"
esac
